package net2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;


public class UdpEchoServer {

    private static final int PORT = 8888;

    public static void main(String[] args) throws IOException{
        DatagramSocket socket = new DatagramSocket(PORT);

        while (true) {
            byte[] bytes = new byte[516];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            System.out.println("等待接收UDP数据报...");
            socket.receive(packet);
            SocketAddress client = packet.getSocketAddress();
            System.out.println("客户端IP：" + client);
            System.out.println("客户端Port：" + packet.getPort());
            System.out.println("客户端发送的原数据：" + packet.getData());
            String response = new String(packet.getData());
            System.out.println("客户端发送的文本数据：" + response);
            byte[] resp = response.getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(resp, resp.length, client);
            socket.send(datagramPacket);
            System.out.println("服务器已发送回显信息...");
        }
    }
}
